package util;

import android.os.AsyncTask;
import android.util.Log;


import com.serecttask.MyApplication;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;

import java.util.HashMap;

/**
 * Created by xiaozhi on 2016/7/1.
 */
public class KsoapUtil extends AsyncTask<String, Integer, String>{
    //soap 链接超时时间
    private  int timeout = 30000;//30s
    private String methodName;
    private HashMap<String,String> params;
    // 命名空间
    private String nameSpace = MyApplication.NAMESPACE;
    // EndPoint
    private String WebServiceUrl = MyApplication.WebServiceUrl;

    private Exception exception;

    private  PostCallback postCallback;
//    public KsoapUtil(Context context,String methodName,HashMap<String,String> params){
//        this.context = context;
//        this.methodName = methodName;
//        this.params = params;
//    }

    public KsoapUtil(String methodName, HashMap<String, String> params, PostCallback postCallback) {
        this.methodName = methodName;
        this.params = params;
        this.postCallback = postCallback;
    }

//
// soap 头部认证 soaphead的验证

    private Element buildAuthHeader(){
        Element hElement = new Element().createElement(nameSpace,"AuthHead");
        //TODO if set name as “authToken”, then in the server side, the “authoToken” will be null
        //hElement.setName(“authToken”);
        Element passwordElement = new Element().createElement(nameSpace,"ilou的md5加密值");
        passwordElement.setName("strSign");
        passwordElement.addChild(Node.TEXT,"1");
        hElement.addChild(Node.ELEMENT, passwordElement);
//        // 定义一个soapheader
//        Element[] header = new Element[1];
//        header[0] = new Element().createElement(_NAMESPACE, "MySoapHeader");
//        Element Name = new Element().createElement(_NAMESPACE, "Name");
//        Name.addChild(Node.TEXT, "user");
//        header[0].addChild(Node.ELEMENT, Name);
//        Element Password = new Element().createElement(_NAMESPACE, "Password");
//        Password.addChild(Node.TEXT, "password");
//        header[0].addChild(Node.ELEMENT, Password);


        return hElement;
    }

    public  String doSoapAction() {
        String result="";
        //soap请求地址
        String soapActionAddress  = nameSpace+methodName;
            try {

            // 指定WebService的命名空间和调用的方法名
            SoapObject soapObject = new SoapObject(nameSpace, methodName);

            // 设置需调用WebService接口需要传入的两个参数mobileCode、userId
            for (String key:params.keySet()){
                soapObject.addProperty(key, params.get(key));
            }


        // 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//      添加头部认证
//        envelope.headerOut = new Element[1];
//        envelope.headerOut[0] = buildAuthHeader();

        envelope.bodyOut = soapObject;
        // 设置是否调用的是dotNet开发的WebService
        envelope.dotNet = true;
        // 等价于envelope.bodyOut = rpc;
        envelope.setOutputSoapObject(soapObject);

        HttpTransportSE transport = new HttpTransportSE(WebServiceUrl,30000);


        // 调用WebService
        transport.call(soapActionAddress, envelope);

        // 获取返回的数据
//        if(envelope.getResponse() != null){
//            SoapObject object = (SoapObject)envelope.getResponse();
//            result = object.getProperty(methodName)+"";
//            System.out.println("result=" + result);
//        }
//        SoapPrimitive result1 = (SoapPrimitive)envelope.getResponse();
//        System.out.println("result1 = "+result1);
        SoapObject object = (SoapObject) envelope.bodyIn;
//        Object object =  envelope.bodyIn;
        result = object.getProperty(0).toString();
//        // 获取返回的结果
//        result = object.toString();

        } catch (Exception e) {
            exception = e;
            return "false";
        }

        return result;
    }


    protected void onFail(Exception e){

    }
    protected void onSuccess(String result){

    }


    //onPreExecute()方法用于在执行异步任务前,主线程做一些准备工作
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("调用onPreExecute()方法--->准备开始执行异步任务");
    }

    public KsoapUtil() {
        super();
    }

    //doInBackground()方法用于在执行异步任务,不可以更改主线程中UI
    @Override
    protected String doInBackground(String... params) {
        Log.e("doInBackground", "调用doInBackground()方法--->开始执行异步任务  params=" + this.params.toString());
        Log.e("上传参数", this.params.toString());
        String result = doSoapAction();
        return result;
    }

   // onPostExecute()方法用于异步任务执行完成后,在主线程中执行的操作
    @Override
    protected void onPostExecute(String result)
    {
        if(result != "false"){
            postCallback.onSuccess(result);
        }else {
            postCallback.onFail(exception);
        }

        System.out.println("调用onPostExecute()方法--->异步任务执行完毕  ");

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onCancelled(String s) {
        super.onCancelled(s);
    }


//    //onProgressUpdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息
//    @Override
//    protected void onProgressUpdate(Integer... values) {
//        super.onProgressUpdate(values);
//        textView.setText("已经加载" + values[0] + "%");
//    }


    //onCancelled()方法用于异步任务被取消时,在主线程中执行相关的操作
//    @Override
//    protected void onCancelled() {
//        super.onCancelled();
//        System.out.println("调用onCancelled()方法--->异步任务被取消");
//    }
}
